﻿using System.Collections.Generic;
using System.IO;
using Sirenix.OdinInspector;
using UnityEngine.Helper;

namespace UnityEngine.UI
{
    public class DynamicAtlasDemo : MonoBehaviour
    {

        public GameObject image;
        public Transform imageParent;
        private int index = 0;
        private List<string> paths = new List<string>();
        private List<DynamicRawImage> images = new List<DynamicRawImage>();
        [FolderPath]
        public string[] serchPath;
        private int pathIndex = 0;

        public void OnAddClick()
        {
            index++;
            var item = imageParent.AddChild(image.gameObject);
            var pos = image.transform.localPosition;
            item.transform.localPosition = new Vector3(pos.x + (index + 1) * 100, pos.y + (index + 1) * 100, 0);

            DynamicRawImage data = item.transform.Find("RawImage/DynamicImage").GetComponent<DynamicRawImage>();
            string imageName = paths[pathIndex];
            data.SetImage(imageName);
            data.gameObject.name = imageName;
            pathIndex++;
            if (pathIndex >= paths.Count)
            {
                pathIndex = 0;
            }
            images.Add(data);
        }

        public void OnSubClick()
        {
            if (images.Count == 0)
            {
                return;
            }
            //int removeIndex = Random.Range(0, images.Count - 1);
            int removeIndex = 0;
            DynamicRawImage obj = images[removeIndex];
            images.RemoveAt(removeIndex);
            GameObject.Destroy(obj.transform.parent.parent.gameObject);
        }

        private void Awake()
        {
            foreach (string s in serchPath)
            {
                if (string.IsNullOrEmpty(s))
                    continue;
                var files = Directory.GetFiles(s, "*.png");
                foreach (string file in files)
                    paths.Add(file.Substring(file.IndexOf("/Resources/")+"/Resources/".Length).Split('.')[0]);
            }
            Debug.Log(string.Join(";",paths));
        }
   
    }
}
